package cn.ltgodm.moj.judge.strategy.impl;

import cn.hutool.json.JSONUtil;
import cn.ltgodm.moj.judge.strategy.JudgeContext;
import cn.ltgodm.moj.judge.strategy.JudgeStrategy;
import cn.ltgodm.moj.model.dto.question.JudgeCase;
import cn.ltgodm.moj.model.dto.question.JudgeConfig;
import cn.ltgodm.moj.model.dto.questionsubmit.JudgeInfo;
import cn.ltgodm.moj.model.entity.Question;
import cn.ltgodm.moj.model.enums.QuestionJudgeInfomessageEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class JavaJudgeStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        log.info("进入java 判题策略");
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> resultOuputList = judgeContext.getOutputCaseList();
        Question question = judgeContext.getQuestion();
        judgeInfo.setMessage(QuestionJudgeInfomessageEnum.ACCEPTED.getValue());

        //获取题目信息中的输出信息
        List<String> outputList = JSONUtil.toList(question.getJudgeCase(), JudgeCase.class).stream().map(JudgeCase::getOutput).collect(Collectors.toList());

        //对比输出信息
        if (outputList.size() != resultOuputList.size()) {
            judgeInfo.setMessage(QuestionJudgeInfomessageEnum.WRONG_ANSWER.getValue());
            return judgeInfo;
        }
        for (int i = 0; i < outputList.size(); i++) {
            String outputCase = outputList.get(i);
            String resultCase = resultOuputList.get(i);
            if (!outputCase.equals(resultCase)) {
                judgeInfo.setMessage(QuestionJudgeInfomessageEnum.WRONG_ANSWER.getValue());
                return judgeInfo;
            }
        }
        //校验判题配置
        JudgeConfig judgeConfig = JSONUtil.toBean(question.getJudgeConfig(), JudgeConfig.class);
        Long memoryLimit = judgeConfig.getMemoryLimit();
        Long timeLimit = judgeConfig.getTimeLimit();
        Long memory = judgeInfo.getMemory() / 1024;
        Long time = judgeInfo.getTime();

        if (memory.compareTo(memoryLimit) > 0) {
            judgeInfo.setMessage(QuestionJudgeInfomessageEnum.MEMORY_LIMIT_EXCEEDED.getValue());
            return judgeInfo;
        }

        if (time.compareTo(timeLimit) > 0) {
            judgeInfo.setMessage(QuestionJudgeInfomessageEnum.TIME_LIMIT_EXCEEDED.getValue());
            return judgeInfo;
        }
        //返回正确结果
        return judgeInfo;
    }
}
